import React from 'react';
import { connect } from 'dva';
//import ReactEcharts from "echarts-for-react";
import ReactEchartsCore from 'echarts-for-react/lib/core';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/geo';
import 'echarts/lib/chart/scatter';
import echarts from 'echarts/lib/echarts';
import world from '../../../assets/world'

echarts.registerMap('world', world);

class Map extends React.Component {
  constructor(props) {
    super(props);
  }

  shouldComponentUpdate(nextProps) {
    if (!nextProps.coords || nextProps.coords.length === 0) return false;
    if (!this.props.coords || this.props.coords.length === 0) return true;
    if (this.props.coords.length !== nextProps.coords.length) return true;
    for (let i = 0, len = this.props.coords.length; i < len; i++) {
      if (this.props.coords[i][0] !== nextProps.coords[i][0]
        || this.props.coords[i][1] !== nextProps.coords[i][1]
        || this.props.coords[i][2] !== nextProps.coords[i][2]
      ) {
        return true;
      }
    }
    return false;
  }

  render() {
    const option = this.props.coords ? {
      backgroundColor: '#1890ff',

      tooltip: {
        trigger: 'item'
      },
      geo: {
        map: 'world',
        label: {
          emphasis: {
            show: false
          }
        },
        itemStyle: {
          normal: {
            areaColor: 'white',
            borderColor: 'white'
          },
          emphasis: {
            areaColor: 'white'
          }
        }
      },
      series: [{
        type: 'scatter',
        id: 'geoScatter',
        coordinateSystem: 'geo',
        itemStyle: {
          opacity: 1,
          shadowBlur: 5,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        data: this.props.coords,
        symbolSize: 6,
        tooltip: {
          formatter: function(obj) {
            var value = obj.value;
            return value[2];
          }
        }
      }]
    } : null;

    return this.props.coords ? (<ReactEchartsCore echarts={echarts} option={option} style={{height: '350px'}}/>) : null;
  }
}

function uniqueCoords(coords) {
  if (coords.length <= 1) return coords;
  coords.sort((e1, e2) => e1[0] - e2[0]);
  let unique = [coords[0]];
  for (let i = 1, len = coords.length; i < len; i++) {
    if (coords[i][0] !== coords[i-1][0] || coords[i][1] !== coords[i-1][1]) {
      unique.push(coords[i]);
    }
  }
  return unique;
}

function mapStateToProps(state) {
  const { list } = state.node;
  let unorderdCoords = list.map((node) => [node.node_longitude, node.node_latitude, node.node_location]);
  let coords = uniqueCoords(unorderdCoords);
  return {
    coords,
  };
}

export default connect(mapStateToProps)(Map);
